package 面试经典150题.图;

/**
 * @author tmh
 * @date 2024/6/26 21:35
 * @description
 */
public class T695岛屿的最大面积 {
    public int maxAreaOfIsland(int[][] grid) {
        int maxArea = 0;
        int m = grid.length;
        int n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                //遍历所有陆地  格子的值为1，表示这个格子是陆地
                if (grid[i][j] == 1) {
                    int area = area(grid, i, j);
                    maxArea = Math.max(maxArea, area);
                }
            }
        }
        return maxArea;
    }

    public int area(int[][] grid, int r, int c) {
        if (!inArea(grid, r, c)) {
            return 0;
        }
        if (grid[r][c] != 1) {
            return 0;
        }
        //把当前格子标记为已经遍历
        grid[r][c] = 2;
        //返回当前这个岛屿的面积==>当前岛屿的面积=当前陆地的面积加上四个方向上陆地的面积之和
        return 1 + area(grid, r - 1, c)
                + area(grid, r + 1, c)
                + area(grid, r, c - 1)
                + area(grid, r, c + 1);
    }

    public boolean inArea(int[][] grid, int r, int c) {
        return r >= 0 && r < grid.length && c >= 0 && c < grid[0].length;
    }


}
